﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using douban.Core.Utils;
using Newtonsoft.Json;

namespace douban.Core.Apis
{
    public class Authenticate
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }

        [JsonProperty("douban_user_name")]
        public string UserName { get; set; }

        [JsonProperty("douban_user_id")]
        public string UserId { get; set; }

        [JsonProperty("expires_in")]
        public string ExpiresIn { get; set; }

        [JsonProperty("refresh_token")]
        public string RefreshToken { get; set; }

        [JsonProperty("token_time")]
        public DateTime GetTokenTime { get; set; }

        public void SetCommon()
        {
            Common.Token = AccessToken;
            Common.UserId = UserId;
            Common.RefreshToken = RefreshToken;
            Common.ExpiresIn = ExpiresIn;
            Common.UserName = UserName;
            Common.TokenTime = GetTokenTime;
        }
    }

    public static partial class Api
    {
        private const string AuthUrl = "https://www.douban.com:443/service/auth2/token";

        internal static async Task<Authenticate> AuthGetToken(string userName, string password)
        {
            var json = await WebUtil.Post(AuthUrl, new[]
            {
                new KeyValuePair<string, string>("client_id", Common.API_KEY),
                new KeyValuePair<string, string>("redirect_uri", Common.REDIRECT_URI),
                new KeyValuePair<string, string>("grant_type", Common.GRANT_TYPE),
                new KeyValuePair<string, string>("client_secret", Common.CLIENT_SECRET),
                new KeyValuePair<string, string>("username", userName),
                new KeyValuePair<string, string>("password", password),
            });
            var authenticate = JsonUtil.Deserialize<Authenticate>(json);

            authenticate.GetTokenTime = DateTime.Now;
            return authenticate;
        }
    }
}
